package com.wdhcr.controller.admin;

import com.wdhcr.entity.User;
import com.wdhcr.enums.ResultCode;
import com.wdhcr.service.UserService;
import com.wdhcr.utils.JwtUtil;
import com.wdhcr.utils.ResponseResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@RestController
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private JwtUtil jwtUtil;

    @CrossOrigin
    @PostMapping("/getRole")
    public ResponseResult getRole(){
//        System.out.println("获取橘色权限");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("Authorization");
        if (token == null){
            return new ResponseResult(ResultCode.FAIL.getCode(),"获取失败！请重试！！",null);
        }
        Claims claims = jwtUtil.parseToken(token);
        String id = claims.getId();
        String openid = claims.getSubject();
        System.out.println(openid+"--------------------------------------");
        User byOpenid = userService.findByOpenid(openid);
        if (byOpenid != null){
            if ("admin".equals(byOpenid.getRole()))
            return new ResponseResult(ResultCode.SUCCESS.getCode(),"你好管理员，欢迎回来！！",byOpenid.getRole());
            return new ResponseResult(ResultCode.SUCCESS.getCode(),"欢迎你的到来！！",byOpenid.getRole());

        }
        return new ResponseResult(ResultCode.FAIL.getCode(),"无效token！请重试！！",null);

    }


}
